﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.ETL
{
    public partial class BFileUploadEditor : Form, IComponentEditor 
    {
        private object ownerActivityNode;
        private BFileUploadComponent _BFileUploadComponent;

        /// <summary>
        /// 
        /// </summary>
        public BFileUploadEditor()
        {
            InitializeComponent();
        }

        private void btn_Browse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg=new FolderBrowserDialog();
            if(dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                this.txt_SrcFolder.Text = dlg.SelectedPath;
                this.lbl_TotalFiles.Text =
                    string.Format("There are total of {0} files to be loaded.",
                                  this.GetFileCount(this.txt_SrcFolder.Text, this.txt_Filter.Text,
                                                    this.ck_IncludeSubFolder.Checked));
            }
        }

        private int GetFileCount(string rootFolderPath, string filter, bool includeSubFolder)
        {
            DirectoryInfo dirInfo=new DirectoryInfo(rootFolderPath);
            if(string.IsNullOrEmpty(filter))
            {
                filter = "*.*";
            }
            FileInfo[] files = null;
            if(includeSubFolder)
            {
                files = dirInfo.GetFiles(filter, SearchOption.AllDirectories);
            }
            else
            {
                files = dirInfo.GetFiles(filter, SearchOption.TopDirectoryOnly);
            }
            if (files != null)
                return files.Length;
            else
                return 0;
        }

        private void ck_IncludeSubFolder_CheckedChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_SrcFolder.Text))
            {
                this.lbl_TotalFiles.Text =
                    string.Format("There are total of {0} files to be loaded.",
                                  this.GetFileCount(this.txt_SrcFolder.Text, this.txt_Filter.Text,
                                                    this.ck_IncludeSubFolder.Checked));
            }
        }

        private void txt_Filter_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.txt_SrcFolder.Text))
            {
                this.lbl_TotalFiles.Text =
                    string.Format("There are total of {0} files to be loaded.",
                                  this.GetFileCount(this.txt_SrcFolder.Text, this.txt_Filter.Text,
                                                    this.ck_IncludeSubFolder.Checked));
            }
        }

        private void btn_Refresh_Click(object sender, EventArgs e)
        {
            this.cbo_Tables.Items.Clear();
            this.cbo_Tables.SelectedIndex = -1;
            this.cbo_Tables.Text = string.Empty;

            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text))
            {
                string[] tblNames = DbUtil.GetTables(this.txt_ConnStr.Text);
                foreach(string tblName in tblNames)
                {
                    this.cbo_Tables.Items.Add(tblName);
                }
            }
        }

        private void cbo_Tables_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_ConnStr.Text) && this.cbo_Tables.SelectedIndex>=0)
            {
                string connStr = this.txt_ConnStr.Text;
                string tblName = this.cbo_Tables.SelectedItem.ToString();
                TableColumn[] cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, connStr, string.Empty, tblName);
                this.PopulateTableFields(this.cbo_FileNameField, cols);
                this.PopulateTableFields(this.cbo_FilePathFields, cols);
                this.PopulateTableFields(this.cbo_ImgField, cols);
                this.PopulateTableFields(this.cbo_KeyField, cols);
            }
        }

        private void PopulateTableFields(ComboBox comboBox, TableColumn[] cols)
        {
            comboBox.Items.Clear();
            comboBox.SelectedIndex = -1;
            comboBox.Text = string.Empty;

            foreach(TableColumn col in cols)
            {
                comboBox.Items.Add(col.ColumnName);
            }
        }

        private void BFileUploadEditor_Load(object sender, EventArgs e)
        {

        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get { return ownerActivityNode; }
            set { ownerActivityNode = value; }
        }

        public Type WorkflowComponentType
        {
            get { return typeof(BFileUploadComponent); }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this.ownerActivityNode = activityNode;
            this._BFileUploadComponent = (BFileUploadComponent) wfComponent;

            this.txt_Filter.Text = this._BFileUploadComponent.Filter;
            this.ck_IncludeSubFolder.Checked = this._BFileUploadComponent.IncludeSubFolder;
            this.txt_SrcFolder.Text = this._BFileUploadComponent.SrcFolderPath;

            this.txt_ConnStr.Text = this._BFileUploadComponent.ConnStr;
            this.btn_Refresh_Click(this,new EventArgs());
            if(!string.IsNullOrEmpty(this._BFileUploadComponent.TableName) && this.cbo_Tables.Items.Count>0)
            {
                for(int i=0;i<this.cbo_Tables.Items.Count;i++)
                {
                    if(this.cbo_Tables.Items[i].ToString()==this._BFileUploadComponent.TableName)
                    {
                        this.cbo_Tables.SelectedIndex = i;
                        break;
                    }
                }
            }
            
            this.SetComboxValue(this.cbo_FileNameField,this._BFileUploadComponent.FileNameField);
            this.SetComboxValue(this.cbo_FilePathFields,this._BFileUploadComponent.FilePathField);
            this.SetComboxValue(this.cbo_ImgField,this._BFileUploadComponent.ImageFieldName);
            this.SetComboxValue(this.cbo_KeyField,this._BFileUploadComponent.KeyFieldName);
        }

        private void SetComboxValue(ComboBox comboBox, string value)
        {
            comboBox.Text = value;
            if (comboBox.Items.Count > 0 && (!string.IsNullOrEmpty(value)))
            {
                for (int i = 0; i < comboBox.Items.Count; i++)
                {
                    if (comboBox.Items[i].ToString() == value)
                    {
                        comboBox.SelectedIndex = i;
                        break;
                    }
                }
            }
        }

        public void SaveSettings()
        {
            this._BFileUploadComponent.SrcFolderPath = this.txt_SrcFolder.Text;
            this._BFileUploadComponent.Filter = this.txt_Filter.Text;
            this._BFileUploadComponent.IncludeSubFolder = this.ck_IncludeSubFolder.Checked;

            this._BFileUploadComponent.ConnStr = this.txt_ConnStr.Text;
            this._BFileUploadComponent.TableName = this.cbo_Tables.SelectedItem.ToString();
            this._BFileUploadComponent.FileNameField = this.cbo_FileNameField.Text;
            this._BFileUploadComponent.FilePathField = this.cbo_FilePathFields.Text;
            this._BFileUploadComponent.ImageFieldName = this.cbo_ImgField.Text;
            this._BFileUploadComponent.KeyFieldName = this.cbo_KeyField.Text;

        }

        public TestResult Test()
        {
            try
            {
                this.SaveSettings();
                BFileUploadInstruction instruction =
                    new BFileUploadInstruction(this._BFileUploadComponent.ComponentID, Guid.Empty,
                                               this._BFileUploadComponent.SrcFolderPath,
                                               this._BFileUploadComponent.Filter,
                                               this._BFileUploadComponent.IncludeSubFolder,
                                               this._BFileUploadComponent.ConnStr, this._BFileUploadComponent.TableName,
                                               this._BFileUploadComponent.FileNameField,
                                               this._BFileUploadComponent.FilePathField,
                                               this._BFileUploadComponent.ImageFieldName,
                                               this._BFileUploadComponent.KeyFieldName);
                BFileUploadWorker worker = new BFileUploadWorker();
                worker.SetInstruction(Guid.NewGuid(), instruction, string.Empty, this._BFileUploadComponent.ComponentName);
                worker.DoWork();

                return new TestResult(true,"Finished");
            }
            catch(Exception ex)
            {
                return new TestResult(false,ex.ToString());
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if(this.UpdateComponentSettingEvent !=null)
            {
                this.UpdateComponentSettingEvent(this.ownerActivityNode, this._BFileUploadComponent);
            }
            this.Close();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Test_Click(object sender, EventArgs e)
        {
            TestResult result = this.Test();
            MessageBox.Show(result.Message, result.Succeed.ToString());
        }
    }
}
